package com.code.test.first.tree;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Stack;

public class InterateNode {

    public static void main(String[] args) {
        TreeNode left10 = new TreeNode(1, null, null);
        TreeNode right20 = new TreeNode(2, null, null);
//        TreeNode left30 = new TreeNode(30, null, null);
//        TreeNode right40 = new TreeNode(40, null, null);
        TreeNode left3 = new TreeNode(4, left10, right20);
        TreeNode right5 = new TreeNode(6, null,null);
        TreeNode root = new TreeNode(5, left3, right5);

        List<Integer> list = traversalMid(root);
        System.out.println(list);
    }

    static List<Integer> traversalFront(TreeNode cur) {
        if (cur == null) {
            return Collections.emptyList();
        }
        Stack<TreeNode> stack = new Stack<>();
        stack.add(cur);

        List<Integer> ret = new ArrayList<>();
        while (!stack.isEmpty()) {
            TreeNode node = stack.pop();

            ret.add(node.val);

            if (node.right != null) {
                stack.push(node.right);
            }
            if (node.left != null) {
                stack.push(node.left);
            }
        }
        return ret;
    }

    static List<Integer> traversalMid(TreeNode root) {

        Stack<TreeNode> stack = new Stack<>();
        stack.add(root);

        List<Integer> ret = new ArrayList<>();

        while (!stack.isEmpty()) {
            TreeNode node = stack.peek();
            if (node != null) {
                stack.pop();
                if (node.right != null) {
                    stack.push(node.right);
                }

                stack.push(node);
                stack.push(null);
                if (node.left != null) {
                    stack.push(node.left);
                }
            } else {
                stack.pop();
                node = stack.peek();
                stack.pop();
                ret.add(node.val);
            }
        }
        return ret;
    }

}
